package com.basic.aqs;

import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

@SuppressWarnings("all")
public class ReentrantReadWriteLockTest {

	private static final ReentrantReadWriteLock READ_WRITE_LOCK = new ReentrantReadWriteLock();
	private static final ReadLock readLock = READ_WRITE_LOCK.readLock();
	private static final  WriteLock writeLock = READ_WRITE_LOCK.writeLock();
	
	public static void main(String[] args) {
		
		Thread r1 = new Thread(new Runnable() {
			
			public void run() {
				try {
					Thread.sleep(0);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				try {
					readLock.lock();
					System.out.println("r1 lock");
				}finally{
					readLock.unlock();
					System.out.println("r1 unlock");
				}
			}
		});
		
		Thread r2 = new Thread(new Runnable() {
			
			public void run() {
				try {
					Thread.sleep(0);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				try {
					readLock.lock();
					System.out.println("r2 lock");
				}finally{
					readLock.unlock();
					System.out.println("r2 unlock");
				}
			}
		});
		
		Thread w1 = new Thread(new Runnable() {
			
			public void run() {
				try {
					Thread.sleep(0);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				try {
					writeLock.lock();
					System.out.println("w1 lock");
				}finally{
					writeLock.unlock();
					System.out.println("w1 lock");
				}
			}
		});
		
		r1.start();
		r2.start();
		w1.start();
		Thread.currentThread().yield();
	}
}
